unit WebAPI.Factory;

interface

uses
  WebAPI.Intf, WebAPI.Abstract, JSON, Generics.Collections;

type
  /// <summary>
  ///  This factory creates objects, that inherit from TAbstractAPI, which implements the IWebAPI interface
  ///
  /// </summary>
  TWebAPIFactory = class
  strict private
    class var fAPIs: TDictionary<string, TAbstactAPIClass>;
  public
    class constructor Create;
    class destructor Destroy;
    /// <param name="aVersion">The Version of the API</param>
    /// <returns>a new instance of an IWebAPI interface with the requested version</returns>
    /// <exception cref="SysUtils.Exception">raised when the version is not found</exception>
    class function newAPI(const aVersion: string): IWebAPI;
    /// <param name="aVersion">the version under which the class gets registered</param>
    /// <param name="aClass">the class of the registered API</param>
    class procedure RegisterAPI(const aVersion: string; const aClass: TAbstactAPIClass);
    /// <returns>a TArray&lt;string&gt; with all registered versions</returns>
    class function getRegisteredVersions : TArray<string>;
  end;

implementation

uses
  SysUtils;

{ TWebAPIFactory }

class constructor TWebAPIFactory.Create;
begin
  fAPIs := TDictionary<string, TAbstactAPIClass>.Create;
end;

class destructor TWebAPIFactory.Destroy;
begin
  fAPIs.Free;
end;

class function TWebAPIFactory.getRegisteredVersions: TArray<string>;
var
  i: Integer;
begin
  setlength(result, fAPIs.Count);
  for i := 0 to fAPIs.Count-1 do
  begin
    result[i] := fAPIs.Keys[i];
  end;
end;

class function TWebAPIFactory.newAPI(const aVersion: string): IWebAPI;
begin
  if fAPIs.ContainsKey(aVersion) then
  begin
    result := fAPIs[aVersion].Create;
  end
  else
    raise Exception.Create('API Version "' + aVersion + '" not found');
end;

class procedure TWebAPIFactory.RegisterAPI(const aVersion: string; const aClass: TAbstactAPIClass);
begin
  fAPIs.Add(aVersion, aClass);
end;

end.
